package com.ruike.alisurface.Serials;

import com.ruike.alisurface.utils.ThreadUtils;
import com.voodoo.lib_utils.ByteUtils;
import com.voodoo.lib_utils.L;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Author：voodoo
 * CreateTime：2021/10/21 021 上午 11:16:10
 * Description：反扫设备扫码
 */
public class BackSweepUtils {

    static Timer timer;
    static TimerTask timerTask;
    static boolean isStop = true; // 是否结束了（停止扫码）
    static byte[] tempBytes;

    public static void initListener() {
        Ttys1Utils.getInstance().setOnSerialPortResultDataListener((resultDataStr, resultBytes) -> {
            if (resultBytes.length > 6) {
                if (resultBytes[0] == (byte) 0x02 && resultBytes[1] == (byte) 0x00) {
                    if (resultBytes[2] == (byte) 0x00) {
                        // 设置成功
                        L.i("寻码指令发送成功");
                        return;
                    }
                }

                if (resultBytes[resultBytes.length - 1] == 0x0D || resultBytes[resultBytes.length - 1] == 0x0A || (resultBytes[resultBytes.length - 2] == 0x0D && resultBytes[resultBytes.length - 1] == 0x0A)) {
                    if (tempBytes == null) {
                        tempBytes = resultBytes;
                        L.iTag("ttys1", "一次返回完整指令");
                    } else {
                        L.iTag("ttys1", "结尾指令，需要拼接到之前的数组中");
                        byte[] mTempBytes = new byte[tempBytes.length + resultBytes.length];
                        L.iTag("ttys1", "mTempBytes:" + ByteUtils.byteArrToHex(mTempBytes));
                        System.arraycopy(tempBytes, 0, mTempBytes, 0, tempBytes.length);
                        L.iTag("ttys1", "mTempBytes:" + ByteUtils.byteArrToHex(mTempBytes));
                        System.arraycopy(resultBytes, 0, mTempBytes, tempBytes.length, resultBytes.length);
                        L.iTag("ttys1", "mTempBytes:" + ByteUtils.byteArrToHex(tempBytes));
                        tempBytes = mTempBytes;
                        L.iTag("ttys1", ByteUtils.byteArrToHex(tempBytes));
                    }
                } else {
                    if (tempBytes == null) {
                        tempBytes = new byte[resultBytes.length];
                    }
                    System.arraycopy(resultBytes, 0, tempBytes, 0, tempBytes.length);
                    L.iTag("ttys1", "指令不全，等待指令中");
                    return;
                }

                String resultPrintStr = hex2CharString(tempBytes);
                tempBytes = new byte[0];
                tempBytes = null;
                L.iTag("ttys1", "扫码返回数据：" + resultPrintStr);
                if (isStop) {
                    L.iTag("ttys1", "已经停止读取数据，不会做回调结果：" + resultPrintStr);
                    return;
                }
                cancelScanning();
                if (mOnScanningResultListener != null) {
                    ThreadUtils.postUI(() -> mOnScanningResultListener.onResultListener(resultPrintStr));
                }
            }
        });
    }

    /**
     * 开启扫码
     */
    public static void startScanning() {
        cancelScanning();
        isStop = false;
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                sendCommandCode();
            }
        };
        timer.schedule(timerTask, 10, 20_000);
    }

    /**
     * 结束扫码
     */
    public static void cancelScanning() {
        isStop = true;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    /**
     * 复位
     */
    public static void restore() {
        cancelScanning();
        sendCommandRestore();
    }

    /**
     * 发送寻码指令 据说发一次有效时长为20秒，所以需要20秒一发
     */
    private static void sendCommandCode() {
        byte[] sendBytes = new byte[9];
        int index = 0;
        sendBytes[index++] = 0x7E;
        sendBytes[index++] = 0x00;
        sendBytes[index++] = 0x08;
        sendBytes[index++] = 0x01;
        sendBytes[index++] = 0x00;
        sendBytes[index++] = 0x02;
        sendBytes[index++] = 0x01;
        sendBytes[index++] = (byte) 0xAB;
        sendBytes[index] = (byte) 0xCD;
        Ttys1Utils.getInstance().SendPort(ByteUtils.byteArrToHex(sendBytes));
    }

    /**
     * 恢复出厂设置
     */
    private static void sendCommandRestore() {
        byte[] sendBytes = new byte[9];
        int index = 0;
        sendBytes[index++] = 0x7E;
        sendBytes[index++] = 0x00;
        sendBytes[index++] = 0x09;
        sendBytes[index++] = 0x01;
        sendBytes[index++] = 0x00;
        sendBytes[index++] = 0x00;
        sendBytes[index++] = (byte) 0xFF;
        sendBytes[index++] = (byte) 0xC0;
        sendBytes[index] = (byte) 0x38;
        Ttys1Utils.getInstance().SendPort(ByteUtils.byteArrToHex(sendBytes));
    }

    /**
     * 16进制ASCII码转字符
     *
     * @param resultBytes
     * @return
     */
    private static String hex2CharString(byte[] resultBytes) {
        StringBuilder stringBuilder = new StringBuilder();
        int end = resultBytes[resultBytes.length - 1] == 0x0D || resultBytes[resultBytes.length - 1] == 0x0A ? 1 : resultBytes[resultBytes.length - 2] == 0x0D && resultBytes[resultBytes.length - 1] == 0x0A ? 2 : 0;
        for (int i = 0; i < resultBytes.length - end; i++) {
            stringBuilder.append((char) Integer.parseInt(ByteUtils.byteToHex(resultBytes[i]), 16));
        }
        return stringBuilder.toString();
    }

    public static OnScanningResultListener mOnScanningResultListener;

    public static void setOnScanningResultListener(OnScanningResultListener onScanningResultListener) {
        mOnScanningResultListener = onScanningResultListener;
    }

    public interface OnScanningResultListener {
        /**
         * 返回扫码数据
         *
         * @param resultPrintStr 扫码转码之后的明文
         */
        void onResultListener(String resultPrintStr);
    }


}
